#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: t_plans.py
# Author: ChenChangSong
# Date: 2025-10-17

"""
功能描述: 测试计划模块
"""

from math import e
from comm.common_code import *

def get_test_plans(creator='',page=1):
    excel_data = get_excel_data()
    """获取测试计划
    :param creator: 创建人
    :param page: 页码
    """
    # 如果为空，查询所有人的测试计划，否则查询指定创建人下的测试计划
    if creator == '':
        url = f"https://api.tapd.cn/test_plans?workspace_id={excel_data['项目ID']}&access_token={excel_data['access_token']}&page={page}"
    else:
        url = f"https://api.tapd.cn/test_plans?workspace_id={excel_data['项目ID']}&creator={creator}&access_token={excel_data['access_token']}&page={page}"
    payload = {}
    
    response_code, response = api_request(method='GET', url=url, headers={}, data=payload)
    logger.info(f"响应内容: {response}")
    response_data = response['data']
    test_plans_url = ''
    if response_code == 200 and response_data == []:
        logger.info(f"当前用户{creator}下无测试计划")
        log_to_ui_info(f"当前用户{creator}下无测试计划")
        return None
    elif response_code == 200 and response_data != []:
        # 每页显示30个，返回当前数量限制下第N页的数据，默认为1（第一页）
        for index, test_plan in enumerate(response_data):
            test_plans_name = test_plan['TestPlan']['name']
            test_plans_id = test_plan['TestPlan']['id']
            # 根据页码计算正确的起始序号，每页30条记录
            start_index = (page - 1) * 30 + index + 1
            test_plans_url += f"{start_index}、{test_plans_name}：https://www.tapd.cn/{excel_data['项目ID']}/sparrow/test_plan/view/{test_plans_id}\n"  #编辑页面
            # test_plans_url += f"{index+1}、{test_plans_name}：https://www.tapd.cn/{excel_data['项目ID']}/sparrow/test_plan/detail/{test_plans_id}\n"  #执行页面
    else:
        logger.info(f"请求失败，响应码：{response_code}")
        log_to_ui_info(f"请求失败，响应码：{response_code}")
        return None
    logger.info(f"\n提示：Ctrl+鼠标左键点击RUL可打开URL\n第{page}页测试计划URL:\n{test_plans_url}")
    log_to_ui_info(f"\n提示：Ctrl+鼠标左键点击RUL可打开URL\n第{page}页测试计划URL:\n{test_plans_url}")
    logger.info(f'↑↑↑=================================================↑↑↑')
    return test_plans_url

def create_test_plan(test_plan_name):
    """创建测试计划
    :param test_plan_name: 测试计划名称
    :param workspace_id: 工作空间ID
    :param access_token: 访问令牌
    """
    excel_data = get_excel_data()
    url = "https://api.tapd.cn/test_plans"

    payload=f'name={test_plan_name}&workspace_id={excel_data["项目ID"]}&access_token={excel_data["access_token"]}&creator={excel_data["创建人"]}'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'}
    response_code, response = api_request(method='POST', url=url, headers=headers, data=payload)
    logger.info(f"响应内容: {response}")
    if response_code == 200 and 'data' in response and 'TestPlan' in response['data'] and 'id' in response['data']['TestPlan']:
        
        test_plan_id = response['data']['TestPlan']['id']
        test_plans_data = ''
        data1 = f"\n创建成功，测试计划ID: {test_plan_id},测试计划标题及链接如下(Ctrl+鼠标左键可打开URL)：\n【{test_plan_name}】\n"
        test_plans_url = f"https://www.tapd.cn/{excel_data['项目ID']}/sparrow/test_plan/view/{test_plan_id}\n" #编辑页面
        test_plans_data += data1 + test_plans_url

        logger.info(f"{test_plans_data}")
        log_to_ui_info(f"{test_plans_data}")
        logger.info(f'↑↑↑=================================================↑↑↑')
        return test_plans_data
    else:
        logger.error(f"创建失败，响应状态码: {response_code}，响应内容: {response}")
        log_to_ui_error(f"创建失败，响应状态码: {response_code}，响应内容: {response}")
        logger.info(f'↑↑↑=================================================↑↑↑')
        return None


def delete_test_plan(test_plan_id):
    excel_data = get_excel_data()
    """删除测试计划
    """
    url = f"https://www.tapd.cn/{excel_data["项目ID"]}/sparrow/test_plan/delete/{test_plan_id}?action_timestamp=90010451&ref_workspace_id={excel_data["项目ID"]}&back_url=https%3A%2F%2Fwww.tapd.cn%2F54682430%2Fsparrow%2Ftest_plan%2Fplan_list%3Fdata%5BFilter%5D%5Bname%5D%3D%26data%5BFilter%5D%5Bowner%5D%3D%26async%3D1%26select_workspace%3D54682430"

    payload={}
    headers = {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'accept-language': 'zh-CN,zh;q=0.9',
    'priority': 'u=0, i',
    'referer': f'https://www.tapd.cn/{excel_data["项目ID"]}/sparrow/test_plan/plan_list?data[Filter][name]=&data[Filter][owner]=&async=1&select_workspace={excel_data["项目ID"]}&cur_test_plan_id={test_plan_id}',
    'sec-ch-ua': '"Not;A=Brand";v="99", "Google Chrome";v="139", "Chromium";v="139"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'document',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-user': '?1',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36',
    'Cookie': excel_data['Cookie']}

    response_code, response = api_request(method="GET", url=url, headers=headers, data=payload)

    logger.info(f"响应内容: {response}")
    logger.info(f"已执行删除测试计划ID: {test_plan_id}")
    log_to_ui_info(f"已执行删除测试计划ID: {test_plan_id}")
    logger.info(f'↑↑↑=================================================↑↑↑')

if __name__ == "__main__":
    # get_test_plans(creator='陈昌松', page=1)
    
    # delete_test_plan('1166606973001000479')

    create_test_plan('【ccs3】本地测试')